#include "IIC_Bus.h"

const int8_t i2c_port = 1;
const uint32_t i2c_frequency = 400000;
const int8_t sda_num = 33;
const int8_t scl_num = 32;

void IIC_Init(void)
{
  Wire.begin(sda_num, scl_num, i2c_frequency);
}

uint32_t drv_i2c_getclock(void)
{
  return Wire.getClock();
}

void drv_i2c_setclock(uint32_t clock)
{
  Wire.setClock(clock);
}

bool IIC_Write(uint8_t addr, uint8_t *data, uint16_t len)
{
  uint8_t res;

  Wire.beginTransmission(addr);
  Wire.write(data, len);
  res = Wire.endTransmission();
  if(res == I2C_ERROR_OK)
  {
    return true;
  }
  else 
  {
    Serial.printf("i2c %02x %d\r\n", addr, res);
    return false;
  }
}

bool drv_i2c_read(uint8_t addr, uint8_t *data, uint16_t len)
{
  uint8_t res;

  res = Wire.requestFrom(addr, len);
  if(res == 0)
  {
    return false;
  }

  while (Wire.available())
  {                        // slave may send less than requested
    *data++ = Wire.read(); // receive a byte as character
  }
  return true;
}
